package com.tzy.note.base.thread.create;

/**
 * 实现Runnable接口多个线程同时操作同一个对象
 * 买火火票的例子
 * 发现线程并发问题：多个线程操作同一个资源的情况下，线程不全安,
 *      1.存在不同线程买到同一张票的可能，
 *      2.存在买到第0或-1张票的可能
 */
public class CreateThread2_SaleTicket implements Runnable {
    //票数
    private int ticketNums = 10;
    @Override
    public void run(){
        while (true){
            if(ticketNums <= 0){
                break;
            }
            //模拟延迟
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + "-->买到了第" + ticketNums-- +"票");
        }
    }

    public static void main(String[] args) {
        CreateThread2_SaleTicket saleTicket = new CreateThread2_SaleTicket();
        new Thread(saleTicket,"tzy1").start();
        new Thread(saleTicket,"tzy2").start();
        new Thread(saleTicket,"tzy3").start();
    }
}
